package com.example.demo.leetcode;

import java.util.Stack;

/**
 * 给你一个字符串数组 tokens ，表示一个根据 逆波兰表示法 表示的算术表达式。
 * <p>
 * 请你计算该表达式。返回一个表示表达式值的整数。
 * <p>
 * 注意：
 * <p>
 * 有效的算符为 '+'、'-'、'*' 和 '/' 。<br>
 * 每个操作数（运算对象）都可以是一个整数或者另一个表达式。<br>
 * 两个整数之间的除法总是 向零截断 。<br>
 * 表达式中不含除零运算。<br>
 * 输入是一个根据逆波兰表示法表示的算术表达式。<br>
 * 答案及所有中间计算结果可以用 32 位 整数表示。<br>
 *<p>
 * <p>
 * 示例 1：
 * <p>
 * 输入：tokens = ["2","1","+","3","*"] <br>
 * 输出：9 <br>
 * 解释：该算式转化为常见的中缀算术表达式为：((2 + 1) * 3) = 9 <br>
 *<p>
 * <p>
 * 示例 2： <br>
 * <p>
 * 输入：tokens = ["4","13","5","/","+"]
 * 输出：6
 * 解释：该算式转化为常见的中缀算术表达式为：(4 + (13 / 5)) = 6
 *<p>
 * <p>
 * 示例 3：
 * <p>
 * 输入：tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"] <br>
 * 输出：22 <br>
 * 解释：该算式转化为常见的中缀算术表达式为:<br>
 * ((10 * (6 / ((9 + 3) * -11))) + 17) + 5 <br>
 * = ((10 * (6 / (12 * -11))) + 17) + 5 <br>
 * = ((10 * (6 / -132)) + 17) + 5 <br>
 * = ((10 * 0) + 17) + 5 <br>
 * = (0 + 17) + 5 <br>
 * = 17 + 5 <br>
 * = 22 <br>
 */
public class _155_逆波兰表达式求值 {

    public static void main(String[] args) {
        String[] tokens = {"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
        int i = new Solution().evalRPN(tokens);
        System.out.println(i);
    }


    private static class Solution {
        /**
         * 用栈来模拟
         * 时间复杂度O(n)
         * 空间复杂度O(n)
         */
        public int evalRPN(String[] tokens) {
            Stack<Integer> stack = new Stack<>();
            Integer first;
            Integer second;
            for (int i = 0; i < tokens.length; i++) {
                switch (tokens[i]) {
                    case "+":
                        first = stack.pop();
                        second = stack.pop();
                        stack.push(second + first);
                        break;
                    case "-":
                        first = stack.pop();
                        second = stack.pop();
                        stack.push(second - first);
                        break;
                    case "*":
                        first = stack.pop();
                        second = stack.pop();
                        stack.push(second * first);
                        break;
                    case "/":
                        first = stack.pop();
                        second = stack.pop();
                        stack.push(second / first);
                        break;
                    default:
                        stack.push(Integer.valueOf(tokens[i]));
                }
            }
            return stack.pop();
        }
    }
}